import { Input, InputNumber, Select } from '@/components/AntdProxy';
import CommonDrawer from '@/components/CommonDrawer';
import { CrudFormLayout } from '@/components/Crud';
import { ChargeStationSelect } from '@/components/CustomForm';
import { CHARGE_TYPE_OPTIONS } from '@/constants/enums';
import { REQUIRED } from '@/constants/rules';
import request from '@/utils/request';
import { useAsyncEffect } from 'ahooks';
import { Form, message } from 'antd';

const Save = (props) => {
  const { open, record, onCancel, onOk } = props;
  const [form] = Form.useForm();

  useAsyncEffect(() => {
    if (open && record) {
      form?.setFieldsValue(record);
    }
  }, [open, record]);

  const handleOk = async () => {
    const values = await form.validateFields();
    const url = record
      ? '/datas/charge/device/update'
      : '/datas/charge/device/add';
    const params = {
      ...values,
    };
    if (record) {
      params.chargeDeviceId = record?.chargeDeviceId;
    }
    await request({
      url,
      method: 'POST',
      data: params,
    });
    message.success('操作成功');
    onOk?.();
  };

  return (
    <CommonDrawer
      title={record ? '编辑' : '新建'}
      open={open}
      onClose={onCancel}
      onOk={handleOk}
      afterOpenChange={(visible) => {
        if (!visible) {
          form.resetFields();
        }
      }}
      width={400}
      destroyOnHidden
    >
      <Form form={form} layout="vertical">
        <CrudFormLayout itemMinWidth={250}>
          <Form.Item
            label="设备编号"
            name="chargeDeviceCode"
            rules={[REQUIRED]}
          >
            <Input placeholder="请输入设备编号" />
          </Form.Item>
          <Form.Item
            label="设备名称"
            name="chargeDeviceName"
            rules={[REQUIRED]}
          >
            <Input placeholder="请输入设备名称" />
          </Form.Item>
          <Form.Item label="充电站" name="chargeStationId" rules={[REQUIRED]}>
            <ChargeStationSelect />
          </Form.Item>
          <Form.Item label="充电类型" name="chargeType" rules={[REQUIRED]}>
            <Select options={CHARGE_TYPE_OPTIONS} />
          </Form.Item>
          <Form.Item label="功率" name="powers">
            <InputNumber addonAfter="kw" />
          </Form.Item>
          <Form.Item label="备注" name="remark">
            <Input />
          </Form.Item>
        </CrudFormLayout>
      </Form>
    </CommonDrawer>
  );
};

export default Save;
